package com.ljdemo.timemanager.ui.screen.mainnav.home

import android.app.Activity
import android.content.pm.ActivityInfo
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.animation.scaleIn
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.viewmodel.compose.viewModel
import com.ljdemo.timemanager.ui.components.LoadingProgress
import com.ljdemo.timemanager.ui.screen.mainnav.MainViewModel
import com.ljdemo.timemanager.ui.theme.TimeManagerTheme
import kotlinx.coroutines.delay

@OptIn(ExperimentalAnimationApi::class)
@Composable
fun HomeView(mainViewModel: MainViewModel) {
//    val homeViewModel:HomeViewModel= viewModel()
    val homeViewModel:HomeViewModel= hiltViewModel()
    val timeState by homeViewModel.timeState.collectAsState()
    val uiState by homeViewModel.uiState.collectAsState()
    val dateState by homeViewModel.dateState.collectAsState()
    val activity= LocalContext.current as Activity // 获取当前activity，此页面只是一个View，activity为MainActivity
    // TODO 和保存沉浸式状态冲突，删了
//    // 以委托的方式获取屏幕方向，屏幕发生旋转会自动改变这个变量，纵向为1，横向为2
//    val screenOrientationState by
//        rememberUpdatedState(newValue = LocalConfiguration.current.orientation)
//
//    // 开启协程监听 屏幕方向变量 变化
//    LaunchedEffect(screenOrientationState){
//        // 屏幕方向变量 变化会调用此方法
//        if (screenOrientationState == 1){
//            // 修改 switch组件为不选中
//            homeViewModel.sendUIIntent(UIIntent.ChangeImmersionState(false))
//        }else{
//            // 修改 switch组件为选中
//            homeViewModel.sendUIIntent(UIIntent.ChangeImmersionState(true))
//        }
//    }
    // 开启协程监听 switch组件是否被选中
    LaunchedEffect(uiState.immersionShow){
        homeViewModel.sendUIIntent(UIIntent.ChangeLoadingState(true))
        if (uiState.immersionShow){
            mainViewModel.changeBottomState(false)
        }else{
            mainViewModel.changeBottomState(true)
        }
        delay(500)
        if (uiState.immersionShow){
            // 屏幕方向改为横向，这样会锁死屏幕旋转，开启系统的自动旋转不会生效
            activity.requestedOrientation=ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
        }else{
//            // 屏幕方向改为竖向，这样会锁死屏幕旋转，开启系统的自动旋转不会生效
            activity.requestedOrientation=ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
            // 设置屏幕旋转方向跟随系统
//            activity.requestedOrientation=ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
        }
        homeViewModel.sendUIIntent(UIIntent.ChangeLoadingState(false))
    }
    Box(modifier = Modifier.background(MaterialTheme.colorScheme.background)) {
        Column(
            modifier = Modifier
                .fillMaxSize() // 设置布满整个父元素
                .padding(10.dp)
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween
            ) {

                AnimatedVisibility(
                    visible = !uiState.immersionShow,
                    enter = scaleIn()
                ) {
                    Row {
                        var pmActive=when(uiState.timeMode){
                            TimeMode.PM -> true
                            TimeMode.AM -> false
                        }
                        OutlinedButton(
                            onClick = { /*TODO*/ },
                            colors = ButtonDefaults.buttonColors(
                                containerColor = if (pmActive) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.primaryContainer
                            ),
                            shape = RoundedCornerShape(topStart = 10.dp, bottomStart = 10.dp)
                        ) {
                            Text(text = "PM",
                                color = if (pmActive) MaterialTheme.colorScheme.onPrimary else MaterialTheme.colorScheme.onPrimaryContainer)
                        }
                        OutlinedButton(
                            onClick = { /*TODO*/ },
                            colors = ButtonDefaults.buttonColors(
                                containerColor = if (!pmActive) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.primaryContainer
                            ),
                            shape = RoundedCornerShape(topEnd = 10.dp, bottomEnd = 10.dp)
                        ) {
                            Text(text = "AM",
                                color = if (!pmActive) MaterialTheme.colorScheme.onPrimary else MaterialTheme.colorScheme.onPrimaryContainer)
                        }
                    }
                }

                Spacer(modifier = Modifier
                    .fillMaxWidth()
                    .weight(1f))

                Switch(
                    checked = uiState.immersionShow,
                    onCheckedChange = {
                        homeViewModel.sendUIIntent(UIIntent.ChangeImmersionState(!uiState.immersionShow))
                    }
                )
            }
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .weight(1f),
                verticalArrangement = Arrangement.Center, // 垂直居中
                horizontalAlignment = Alignment.CenterHorizontally // 水平居中
            ) {
                Column {

                    AnimatedVisibility(
                        visible = !uiState.immersionShow,
                        enter = scaleIn()
                    ) {
                        Text(text = "${dateState.date} ${dateState.week}",
                            modifier = Modifier.padding(bottom = 15.dp, start = 5.dp)
                        )
                    }

                    Row(verticalAlignment = Alignment.CenterVertically) {
                        TimeTag(timeState.hour)
                        Text(text = ":")
                        TimeTag(timeState.minute)
                        Text(text = ":")
                        TimeTag(timeState.second)
                    }
                }
            }
        }
        if (uiState.loadingShow){
            LoadingProgress()
        }
    }
}

@Composable
fun TimeTag(content:Int){
    Card(
        colors = CardDefaults.cardColors(
            containerColor = MaterialTheme.colorScheme.primaryContainer
        ),
        modifier = Modifier.padding(horizontal = 5.dp)
    ) {
        Text(text = content.toString(), modifier = Modifier.padding(vertical = 10.dp, horizontal = 12.dp))
    }
}

@Preview(showBackground = true)
@Composable
fun HomeViewPriView(){
    TimeManagerTheme {
//        HomeView(mainViewModel)
    }
}